<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class Wan8827ApiService extends ServiceBase
{
    protected $miniprogramList = [
        ['name' => '灵宠召唤','appid' => 'wx88ceba305d69c102','origin_id' => 'gh_448c48cf6e05'],
        ['name' => '精灵召唤','appid' => 'wx3fd88284373c406d','origin_id' => 'gh_57c08374b615'],
        ['name' => '超能灵宠','appid' => 'wx704f9e862cd77a47','origin_id' => 'gh_4986f83a7a6c'],
        ['name' => '精灵激战','appid' => 'wx3f2528d6e58d705e','origin_id' => 'gh_2a6c88165f1c'],
        ['name' => '灵宠训练师','appid' => 'wx1f48df50251d5b8d','origin_id' => 'gh_3f64aa63b6a3'],
        ['name' => '修神录','appid' => 'wxf84c6a37072a73f0','origin_id' => 'gh_e2f9b5fe1c4a'],
    ];
    protected $miniprogramListByOriginId;
    protected $miniprogramListByAppId;

    public function __construct()
    {
        foreach ($this->miniprogramList as $val) {
            $appid = $val['appid'];
            $origin_id = $val['origin_id'];
            $this->miniprogramListByAppId[$appid] = $val;
            $this->miniprogramListByOriginId[$origin_id] = $val;
        }
    }

    public function getOneByOriginId($origin_id)
    {
        return $this->miniprogramListByOriginId[$origin_id] ?? '';
    }

    public function getAccessToken($appid)
    {
        $params = [
            'AppId' => $appid,
            'Sign' => md5("AppId={$appid}"),
        ];

        $url = "https://xapi.h5gamecdn.club:2046/xapi/mp/wx/accesstoken";
        $response = Http::post($url, $params);
        $body = trim($response->body(), '"');
        $data = str_replace('\"', '"', $body);
        $data = json_decode($data, true);
        if (empty($data) || !isset($data['data']['AccessToken'])) {
            yqlog($appid, $body);
            return false;
        }

        return $data['data']['AccessToken'];
    }

    public function generateScheme($appid, $query)
    {
        $access_token = $this->getAccessToken($appid);
        if (!$access_token) {
            return false;
        }

        $params = [
            'jump_wxa' => [
                'query' => $query
            ]
        ];
        $url = "https://xapi.h5gamecdn.club/apiweixinqqcom/wxa/generatescheme?access_token={$access_token}";
        $response = Http::post($url, $params);
        $body = trim($response->body(), '"');
        $data = str_replace('\"', '"', $body);
        $data = json_decode($data, true);
        if (empty($data) || !isset($data['openlink'])) {
            yqlog($appid, $body);
            return false;
        }

        return $data['openlink'];
    }
}
